package cn.xuexiluxian.open.admin.controller.common;

import cn.xuexiluxian.open.common.constant.CacheConstants;
import cn.xuexiluxian.open.common.utils.ImageCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 */
@Slf4j
@RestController
@RequestMapping(value = "captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("imageCode")
    public void imageCode(String key, HttpServletResponse response) throws IOException {
        /*禁止缓存*/
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        /*获取验证码*/
        String code = ImageCodeUtil.generateVerifyCode(4);
        redisTemplate.opsForValue().set(CacheConstants.IMAGE_CAPTCHA_PREFIX + key, code, 5, TimeUnit.MINUTES);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageCodeUtil.outputImage(110, 40, outputStream, code);
        outputStream.flush();
        outputStream.close();
    }

}
